import React from 'react';
import { Table, Icon, Divider, Tag, Alert, Tooltip } from 'antd';
import { useRequest, defaultFormatResult } from '@/hooks';
import {
    getUnSubmitInterviewProcedure,
    setInterviewAbsent,
    cancelInterviewAbsent,
    notifyInterview
} from '../../../service';

const IconButton = ({ iconType, onClick, title, ...rest }) => (
    <Tooltip title={title}>
        <span style={{ cursor: 'pointer' }} onClick={onClick}>
            <Icon type={iconType} {...rest} />
        </span>
    </Tooltip>
);

const TopMsg = ({ content, type }) => <Alert message={content} banner type={type} />;

const msgType = {
    WARNING: 'warning',
    SUCCESS: 'success',
    ERROR: 'error'
};

const defaultMsg = {
    content: '所有参与的面谈官都提交面谈记录后，才能进行面谈总结，如有面谈官缺席，请将其设置为缺席面谈',
    type: msgType.WARNING
};

const Wrapper = React.memo(({ children }) => (
    <div style={{ position: 'relative', display: 'inline-block' }}>
        <div
            style={{
                position: 'absolute',
                left: 0,
                top: '50%',
                width: '100%',
                height: 1,
                transform: 'rotate(45deg)',
                backgroundColor: 'rgba(0, 0, 0, 0.65)',
                pointerEvents: 'none'
            }}
        />
        {children}
    </div>
));

let timer;
export default React.memo(({ arrangeId, setDisabled }) => {
    const [msg, setMsg] = React.useState({
        content: '',
        type: ''
    });

    const { data: dataSource, run: fetchSource, loading } = useRequest(
        () => getUnSubmitInterviewProcedure(arrangeId),
        {
            ...defaultFormatResult
        }
    );

    const [showApiResult, setShowApiResult] = React.useState(false);

    const { run: runNotify } = useRequest(interviewEmployeeCode => notifyInterview({
        arrangeId,
        employeeCodes: [interviewEmployeeCode]
    }), {
        manual: true,
        ...defaultFormatResult
    });

    const { run: runSet } = useRequest(interviewEmployeeCode => setInterviewAbsent({
        arrangeId,
        employeeCodes: [interviewEmployeeCode]
    }), {
        manual: true,
        ...defaultFormatResult
    });

    const { run: runCancel } = useRequest(interviewEmployeeCode => cancelInterviewAbsent({
        arrangeId,
        employeeCodes: [interviewEmployeeCode]
    }), {
        manual: true,
        ...defaultFormatResult
    });

    const handleNotify = async ({ interviewEmployeeCode, interviewEmployeeName }) => {
        const result = await runNotify(interviewEmployeeCode);
        fetchSource();
        if (result) {
            setMsg({
                content: `已发送系统提醒给面谈官 ${interviewEmployeeName}`,
                type: msgType.SUCCESS
            });
        } else {
            setMsg({
                content: `提示面谈官“${interviewEmployeeName}”提交面谈记录失败`,
                type: msgType.ERROR
            });
        }
        setShowApiResult(true);
        if (timer) clearTimeout(timer);
        timer = setTimeout(() => {
            setShowApiResult(false);
        }, 5000);
    };

    const handleAbsent = async ({ interviewEmployeeCode }) => {
        const result = await runSet(interviewEmployeeCode);
        fetchSource();
        console.log(result);
    };

    const handleRollback = async ({ interviewEmployeeCode }) => {
        const result = await runCancel(interviewEmployeeCode);
        fetchSource();
        console.log(result);
    };

    const renderNotifyIcon = record => {
        if (!record.absentInterviewFlag) {
            return (
                <IconButton
                    iconType="bell"
                    title="提醒面谈官"
                    onClick={() => {
                        handleNotify(record);
                    }}
                />
            );
        }
        return <IconButton iconType="bell" style={{ color: '#eee' }} />;
    };

    const renderAbsentIcon = record => {
        if (record.absentInterviewFlag) {
            return (
                <IconButton
                    iconType="rollback"
                    title="取消缺席面谈"
                    onClick={() => {
                        handleRollback(record);
                    }}
                />
            );
        }
        return (
            <Wrapper>
                <IconButton
                    iconType="user"
                    title="设置为缺席面谈"
                    onClick={() => {
                        handleAbsent(record);
                    }}
                />
            </Wrapper>
        );
    };

    // 是否禁用面谈总结按钮
    React.useEffect(() => {
        setDisabled(dataSource?.some(item => !item.absentInterviewFlag));
    }, [dataSource]);

    const renderEmployeeName = (text, record) => {
        const isAbsent = !!record.absentInterviewFlag;
        if (isAbsent) {
            return (
                <>
                    <span style={{ paddingRight: 6, color: 'rgba(127, 127, 127, 0.8)' }}>{text}</span>
                    <Tag closable={false}>缺席面谈</Tag>
                </>
            );
        }
        return <span style={{ paddingRight: 6 }}>{text}</span>;
    };

    const columns = [
        {
            title: '未提交面谈官',
            dataIndex: 'interviewEmployeeName',
            key: 'interviewEmployeeName',
            render: renderEmployeeName
        },
        {
            title: '操作',
            dataIndex: 'interviewEmployeeCode',
            key: 'interviewEmployeeCode',
            render: (text, record) => (
                <>
                    {renderNotifyIcon(record)}
                    <Divider type="vertical" />
                    {renderAbsentIcon(record)}
                </>
            )
        }
    ];

    const showMsg = showApiResult ? msg : defaultMsg;

    const sortDataSource = dataSource?.sort((a, b) => a.absentInterviewFlag - b.absentInterviewFlag);

    return (
        <>
            <TopMsg content={showMsg.content} type={showMsg.type} />
            <div style={{ padding: 16 }}>
                <Table
                    loading={loading}
                    dataSource={sortDataSource}
                    columns={columns}
                    scroll={{ y: 180 }}
                    pagination={false}
                    bordered
                />
            </div>
        </>
    );
});
